<template>
  <div class="personal-center-container">
    <el-row :gutter="20">
      <el-col :lg="8" :md="12" :sm="24" :xl="8" :xs="24">
        <vab-card shadow="hover">
          <div class="personal-center-user-info">
            <el-avatar :size="100" :src="avatar" @click="openDialog" />
            <div class="personal-center-user-info-full-name">
              {{ form.StaffName }}
            </div>
            <div class="personal-center-user-info-description">
              {{ form.description }}
            </div>
            <!-- <div class="personal-center-user-info-follow">
              <el-button round type="primary" @click="dialogVisible = true">
                <vab-icon icon="group-line" />
                修改登录密码
              </el-button>
            </div> -->

            <ul class="personal-center-user-info-list">
              <li v-if="form.CompanyName">
                所属组织：
                <span v-for="(item, index) in form.CompanyName" :key="index">
                  {{ item }}
                  <span v-if="form.CompanyName.length - 1 != index">/</span>
                </span>
              </li>
              <li v-if="form.DepartmentName">
                所属部门：
                <span v-for="(item, index) in form.DepartmentName" :key="index">
                  {{ item }}
                  <span v-if="form.DepartmentName.length - 1 != index">/</span>
                </span>
              </li>
              <li v-if="form.StaffPostRoleName">
                职位岗级：{{ form.StaffPostRoleName }}
              </li>
              <li v-if="form.StaffPostName">
                职位：
                <span v-for="(item, index) in form.StaffPostName" :key="index">
                  {{ item }}
                  <span v-if="form.StaffPostName.length - 1 != index">/</span>
                </span>
              </li>
              <li v-if="form.LoginName">工号：{{ form.LoginName }}</li>
              <!-- <li v-if="form.LoginPassword">密码:{{ form.LoginPassword }}</li> -->
              <li v-if="form.Mobile">手机号：{{ form.Mobile }}</li>
            </ul>
          </div>
        </vab-card>
      </el-col>
      <el-col :lg="8" :md="12" :sm="24" :xl="8" :xs="24">
        <!-- <vab-card shadow="hover">
          <div
            style="
              width: 100%;
              display: flex;
              align-items: center;
              justify-content: center;
              flex-direction: column;
            "
          >
            <div
              id="dd_login"
              style="margin: 0 auto; width: 280px; height: 280px"
            ></div>
            <div style="color: black">钉钉扫码绑定</div>
          </div>
        </vab-card> -->
      </el-col>
      <!-- <el-dialog v-model="dialogVisible" title="修改密码" width="500">
        <div>
          <el-input v-model="LoginPassword" placeholder="请输入新的密码" />
        </div>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="modifyPassword">
              确认修改
            </el-button>
          </div>
        </template>
      </el-dialog> -->
      <!-- <el-col :lg="16" :md="12" :sm="24" :xl="16" :xs="24">
        <vab-card shadow="hover">
          <el-tabs v-model="activeName">
            <el-tab-pane label="基本信息" name="first">
              <el-col :lg="12" :md="16" :sm="24" :xl="12" :xs="24">
                <el-form label-width="80px" :model="form">
                  <el-form-item label="姓名">
                    <el-input v-model="form.fullName" />
                  </el-form-item>
                  <el-form-item label="昵称">
                    <el-input v-model="form.nickname" />
                  </el-form-item>
                  <el-form-item label="性别">
                    <el-select v-model="form.sex" style="width: 100%">
                      <el-option label="保密" :value="0" />
                      <el-option label="男" :value="1" />
                      <el-option label="女" :value="2" />
                    </el-select>
                  </el-form-item>
                  <el-form-item label="个人简介">
                    <el-input v-model="form.description" type="textarea" />
                  </el-form-item>
                  <el-form-item>
                    <template #label>
                      <div style="margin-bottom: 10px">标签</div>
                    </template>
                    <el-tag
                      v-for="tag in dynamicTags"
                      :key="tag"
                      closable
                      :disable-transitions="false"
                      style="
                        margin-right: 10px;
                        margin-bottom: 10px;
                        margin-left: 0;
                      "
                      @close="handleClose(tag)"
                    >
                      {{ tag }}
                    </el-tag>
                    <el-input
                      v-if="inputVisible"
                      ref="inputRef"
                      v-model="inputValue"
                      size="small"
                      style="width: 100px; margin-bottom: 10px"
                      @blur="handleInputConfirm"
                      @keyup.enter="handleInputConfirm"
                    />
                    <el-button
                      v-else
                      size="small"
                      style="margin-bottom: 10px"
                      @click="showInput"
                    >
                      添加
                    </el-button>
                  </el-form-item>
                  <el-form-item>
                    <el-button type="primary" @click="onSubmit">保存</el-button>
                  </el-form-item>
                </el-form>
              </el-col>
            </el-tab-pane>
          </el-tabs>
        </vab-card>
      </el-col> -->
    </el-row>
  </div>
</template>

<script>
  import { useUserStore } from '@/store/modules/user'
  import { getUserInfo, SavePwd } from '@/api/user'
  import { ElMessage } from 'element-plus'

  export default defineComponent({
    name: 'PersonalCenter',
    setup() {
      const $baseMessage = inject('$baseMessage')

      const userStore = useUserStore()
      const { avatar } = storeToRefs(userStore)

      // const _description = decodeURI(
      //   '\u5bcc\u5728\u672f\u6570\uff0c\u4e0d\u5728\u52b3\u8eab\uff1b\u5229\u5728\u52bf\u5c45\uff0c\u4e0d\u5728\u529b\u8015\u3002'
      // )

      const _description = '业精于勤，荒于嬉！天道酬勤，有容乃大！'

      const state = reactive({
        dialogVisible: false,
        LoginPassword: '',
        vabCropperRef: null,
        activeName: 'first',
        form: {
          fullName: '王洪义',
          nickname: 'wanghongyi',
          sex: 1,
          description: _description,
        },
        inputRef: null,
        dynamicTags: ['认真负责', '雷厉风行'],
        inputVisible: false,
        inputValue: '',
      })

      const openDialog = () => {
        state['vabCropperRef'].dialogVisible = true
      }
      const onSubmit = () => {
        $baseMessage('模拟保存成功', 'success', 'vab-hey-message-success')
      }

      const handleClose = (tag) => {
        state.dynamicTags.splice(state.dynamicTags.indexOf(tag), 1)
      }

      const showInput = () => {
        state.inputVisible = true
        nextTick(() => {
          state.inputRef.focus()
        })
      }

      const close = () => {
        state.dialogVisible = false
      }
      const getMsg = async () => {
        const { data } = await getUserInfo()
        state.form = data.UserInfo
        console.log(data, '123123')
      }

      const handleInputConfirm = () => {
        if (state.inputValue) {
          state.dynamicTags.push(state.inputValue)
        }
        state.inputVisible = false
        state.inputValue = ''
      }
      const modifyPassword = async () => {
        if (!state.LoginPassword) {
          ElMessage({
            message: '新密码不能为空!',
            type: 'warning',
          })
          return
        }
        if (state.LoginPassword.length < 6) {
          ElMessage({
            message: '密码不能少于6位',
            type: 'warning',
          })
          return
        }
        const dataMsg = {
          LoginPassword: state.LoginPassword,
        }
        const { code } = await SavePwd(dataMsg)
        if (code == 200) {
          ElMessage({
            message: '修改成功!',
            type: 'success',
          })
          state.dialogVisible = false
          state.LoginPassword = ''
          getMsg()
        }
      }
      onMounted(() => {
        getMsg()
        // ddLogin()
      })

      const ddLogin = () => {
        // const url = state.dingRedirectUrl
        window.DTFrameLogin(
          {
            id: 'dd_login',
            width: 280,
            height: 280,
          },
          {
            redirect_uri: encodeURIComponent('http://192.168.1.12:15001'), //必须和钉钉后台配置的重定向域名一致，这里也可以改成域名，重定向URL也要和浏览器访问的地址保持一致，不然扫码后无反应。
            client_id: 'dingbgbhvnlc84inza6a',
            scope: 'openid',
            response_type: 'code',
            state: randomString(10),
            prompt: 'consent',
          },
          async (loginResult) => {
            const { redirectUrl, authCode } = loginResult
            console.log('loginResult', redirectUrl, authCode)

            state.dingForm = {
              authCode: authCode,
            }
            await dingtalkLogin(state.dingForm).catch(() => {})
            window.location.href = '/#/index'
            // router.push('/')
            // 根据后端提供的接口，向后端传递临时授权码使，用code进行授权
            // try {
            //   state.loading = true
            //   // await dingtalkLogin(getParams).catch(() => {})
            //   await router.push('/')
            // } finally {
            //   state.loading = false
            // }
          },
          (errorMsg) => {
            // 这里一般需要展示登录失败的具体原因
            console.log(errorMsg, '走了几遍errorMsg')
            alert(`Login Error: ${errorMsg}`)
          }
        )
      }
      const randomString = (len) => {
        len = len || 10
        const $chars = 'ABCDEFGHIJKMNOPQRSTUVWXYZ' // 默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1
        const maxPos = $chars.length
        let pwd = ''
        for (let i = 0; i < len; i++) {
          pwd += $chars.charAt(Math.floor(Math.random() * maxPos))
        }
        console.log(pwd, 'pwd')

        return pwd
      }

      return {
        ...toRefs(state),
        avatar,
        openDialog,
        onSubmit,
        randomString,
        ddLogin,
        getMsg,
        showInput,
        modifyPassword,
        handleClose,
        close,
        handleInputConfirm,
      }
    },
  })
</script>

<style lang="scss" scoped>
  $base: '.personal-center';
  #{$base}-container {
    padding: 0 !important;
    background: $base-color-background !important;

    #{$base}-user-info {
      padding: $base-padding;
      text-align: center;

      :deep() {
        .el-avatar {
          img {
            cursor: pointer;
          }
        }
      }

      &-full-name {
        margin-top: 15px;
        font-size: 24px;
        font-weight: 500;
        color: #262626;
      }

      &-description {
        margin-top: 8px;
      }

      &-follow {
        margin-top: 15px;
      }

      &-list {
        margin-top: 18px;
        line-height: 30px;
        text-align: left;
        list-style: none;

        h5 {
          margin: -20px 0 5px;
        }

        :deep() {
          .el-tag {
            margin-right: 10px !important;
          }

          .el-tag + .el-tag {
            margin-left: 0;
          }
        }
      }
    }

    #{$base}-item {
      display: flex;

      i {
        font-size: 40px;
      }

      &-content {
        box-sizing: border-box;
        flex: 1;
        margin-left: $base-margin;

        &-second {
          margin-top: 8px;
        }
      }
    }
  }
</style>
